package cn.sc.summer.warm.handler;

import cn.hutool.http.HttpRequest;
import cn.sc.summer.constant.util.BaseIpUtil;
import cn.sc.summer.constant.warmup.WarmUpConstant;
import cn.sc.summer.token.util.HeaderUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 类名：预热接口处理类
 *
 * @author a-xin
 * @date 16:38
 */
@Slf4j
@Service
public class WarmupHandler {

    /**
     * 预热本地服务
     *
     * @param applicationContext app上下文
     */
    public void warmupLocalhost(ConfigurableApplicationContext applicationContext) {
        StopWatch sw = new StopWatch();
        String port = applicationContext.getEnvironment().getProperty("server.port");
        String localIpAddress = BaseIpUtil.getNacosInstanceIp();
        String url = String.format("http://%s:%s" + WarmUpConstant.WARM_UP, localIpAddress, port);

        sw.start();
        HttpRequest.get(url)
                .header(HeaderUtil.getFeignHeaderList())
                .execute().body();

        log.info("<- The first request time: {} ms", sw.getTime(TimeUnit.MILLISECONDS));
    }

}
